package com.hyq.learn.security.util;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * @author : heyuqin
 * @since : 2024/03/05 17:53
 */
public final class DESUtils {
    public static final String DES_ECB_ENCRYPTION_ALGORITHM = "DES/ECB/PKCS5Padding";


    public static byte[] getKeyBytes(byte[] bytes) {
        return Arrays.copyOf(bytes, 8);
    }

    private static Key getKey(final byte[] key) {
        return new SecretKeySpec(key, "DES");
    }

    public static byte[] encrypt(final byte[] clearBytes, final byte[] keyBytes)
            throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        if (clearBytes == null) {
            throw new IllegalArgumentException("Specified data must not be null");
        }
        if (keyBytes == null) {
            throw new IllegalArgumentException("Specified key must not be null");
        }
        final Cipher cipher = Cipher.getInstance(DES_ECB_ENCRYPTION_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, getKey(keyBytes));
        return cipher.doFinal(clearBytes);
    }

    public static byte[] decrypt(final byte[] cipherBytes, final byte[] keyBytes)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        if (cipherBytes == null) {
            throw new IllegalArgumentException("Specified data must not be null");
        }
        if (keyBytes == null) {
            throw new IllegalArgumentException("Specified key must not be null");
        }
        final Cipher cipher = Cipher.getInstance(DES_ECB_ENCRYPTION_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, getKey(keyBytes));
        return cipher.doFinal(cipherBytes);
    }


}
